<?php
namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function __construct()
    {
    }

    public function index(Request $request) {

        if ($request->ajax()) {

            $rows = $request->get("rows");

            $Role = $this->filters($request, new Role());

            $paginator = $Role->orderBy($request->get("sidx"), $request->get("sord"))->paginate($rows);

            $rows = [];
            foreach ($paginator as $page) {
                $page->platform = "";
                $rows[] = $page;
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view('setting/role/index');
        }
    }

    public function edit(Request $request) {

        $this->validate($request, [
            'id' => 'required',
        ]);

        $oper = $request->get('oper');
        if ($oper == "edit") {
            $role = Role::find($request->get('id'));
            $role->name = $request->get('name');
            $role->save();
        } elseif ($oper == "del") {
            $role = Role::find($request->get('id'));
            $role->delete();
        } elseif ($oper == "add") {
            $role = new Role();
            $role->name = $request->get('name');
            $role->save();
        }

        return response()->json(["success" => true]);
    }
}
